#pragma once
#include <string>
#include <iostream>
#include <ctime>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define NORMAL 0
#define WARING 1
#define ERROR 2
#define FATAL 3

#define LOG_NORMAL "log.normal"
#define LOG_ERR "log.error"
#define MESSAGE_BUFF 1024
#define TIME_BUFF 100


void stamp_to_standard(int stampTime, char* timeString)
{
	time_t tick = (time_t)stampTime;
	struct tm tm;
	tm = *localtime(&tick);
	strftime(timeString, TIME_BUFF-1, "%Y-%m-%d %H:%M:%S", &tm);
}

const char *additionMessage(int degree)
{
    switch (degree)
    {
    case NORMAL:
        return "NORMAL";
    case WARING:
        return "WARING";
    case ERROR:
        return "ERROR";
    case FATAL:
        return "FATAL";
    }
}

void logMessage(int degree, const std::string &error_message)
{
    char buff[MESSAGE_BUFF] = {0};
    char standard_time[TIME_BUFF] = {0};

    stamp_to_standard(time(nullptr), standard_time);
    snprintf(buff, MESSAGE_BUFF - 1, "[%s] [%s] ",
             additionMessage(degree), standard_time);

    FILE *cur = nullptr;
    FILE *normal_fd = fopen(LOG_NORMAL, "a");
    FILE *error_fd = fopen(LOG_ERR, "a");

    if (normal_fd != nullptr && error_fd != nullptr)
    {
        if (degree == NORMAL || degree == WARING)
            cur = normal_fd;
        else if (degree == ERROR || degree == FATAL)
            cur = error_fd;

        fprintf(cur, "%s %s\n", buff, error_message.c_str());
        fclose(normal_fd);
        fclose(error_fd);
    }
}